<template>
  <div class="interactions-container">
    <h1>药物相互作用检测</h1>
    <p class="subtitle">系统正在检测您提供的药物之间可能存在的相互作用</p>
    
    <div v-if="!checked && !loading" class="medications-list">
      <h2>待检测药物列表</h2>
      <p>本系统将分析以下药物之间的相互作用：</p>
      <div class="medications-grid">
        <div 
          v-for="med in medications" 
          :key="med.id" 
          class="medication-card"
        >
          <h3>{{ med.name }}</h3>
          <div v-if="med.rxcui" class="rxnorm-info">
            <p>RxNorm ID: {{ med.rxcui }}</p>
          </div>
        </div>
      </div>
      <button @click="checkInteractions" class="check-btn">开始检测</button>
    </div>
    
    <div v-if="loading" class="loading">
      <p>正在检测药物相互作用...</p>
    </div>
    
    <div v-if="interactions.length > 0" class="interactions-results">
      <h2>检测结果</h2>
      <div 
        v-for="interaction in interactions" 
        :key="interaction.id" 
        class="interaction-item"
        :class="`risk-${interaction.severity.toLowerCase()}`"
      >
        <div class="interaction-header">
          <h3>药物组合：{{ interaction.drugs.join(' + ') }}</h3>
          <span class="severity-badge" :class="getSeverityClass(interaction.severity)">
            {{ getSeverityText(interaction.severity) }}
          </span>
        </div>
        
        <div class="interaction-content">
          <div class="description-section">
            <h4>风险描述</h4>
            <p>{{ interaction.description }}</p>
          </div>
          
          <div class="recommendation-section">
            <h4>处理建议</h4>
            <p>{{ interaction.recommendation }}</p>
          </div>
          
          <div v-if="interaction.fdaData && interaction.fdaData.length > 0" class="fda-data-section">
            <h4>详细相互作用信息</h4>
            <button @click="translateFdaData(interaction)" :disabled="interaction.translating" class="translate-btn">
              {{ interaction.translating ? '翻译中...' : '翻译详细信息' }}
            </button>
            
            <div class="fda-interactions">
              <div 
                v-for="(fdaInteraction, index) in interaction.fdaData" 
                :key="index" 
                class="fda-interaction"
              >
                <h5>{{ fdaInteraction.drug }} 与 {{ fdaInteraction.interactingDrug }} 的相互作用：</h5>
                <ul>
                  <li v-for="(detail, detailIndex) in fdaInteraction.details" :key="detailIndex">
                    {{ detail }}
                  </li>
                </ul>
              </div>
            </div>
            
            <div v-if="interaction.translatedFdaData && interaction.translatedFdaData.length > 0" class="translated-fda-data">
              <h4>翻译后的详细相互作用信息</h4>
              <div class="fda-interactions">
                <div 
                  v-for="(translatedInteraction, index) in interaction.translatedFdaData" 
                  :key="index" 
                  class="fda-interaction"
                >
                  <h5>{{ translatedInteraction.drug }} 与 {{ translatedInteraction.interactingDrug }} 的相互作用：</h5>
                  <ul>
                    <li v-for="(detail, detailIndex) in translatedInteraction.details" :key="detailIndex">
                      {{ detail }}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="!interactions.length && checked && !loading" class="no-interactions">
      <h2>检测结果</h2>
      <p>未发现明显的药物相互作用</p>
    </div>
    
    <div class="api-info">
      <h3>数据来源</h3>
      <p>本系统药物相互作用数据来源于 <a href="https://open.fda.gov" target="_blank">openFDA</a> 公共数据库。</p>
    </div>
    
    <div class="navigation-buttons">
      <button @click="goToNext" class="next-btn">确认并进入患者特征分析</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
// @ts-ignore
import { useStore } from 'vuex'
import openfdaService from '@/services/openfdaService'
import { 
  aiAnalysisService, 
  analyzeDrugInteractionWithSparkHttp,
  generateDetailedAnalysisWithSparkHttp,
  generateRecommendationSummaryWithSparkHttp,
  tencentTranslateService,
  rxnormService
} from '@/services/index'

// 获取路由实例
const router = useRouter()
// 获取store实例
const store = useStore()

// 定义相互作用接口
interface Interaction {
  id: number
  drugs: string[]
  severity: string
  description: string
  recommendation: string
  fdaData?: any[]
  detailedAnalysis?: string
  recommendationSummary?: string
  showDetailedAnalysis?: boolean
  showRecommendationSummary?: boolean
  translating?: boolean
  translatedFdaData?: any[]
  detailedAnalysisLoading?: boolean
  recommendationSummaryLoading?: boolean
}

// 获取药物清单状态
const medications = computed(() => {
  // 统一从Vuex store获取药物清单，确保各页面数据一致性
  // @ts-ignore
  const store = useStore()
  return store.state.medications
})

// 相互作用结果
const interactions = ref<Interaction[]>([])

// 是否已检查
const checked = ref(false)

// 是否正在加载数据
const loading = ref(false)

// AI分析相关状态
const aiAnalysisLoading = ref(false)
const aiAnalysisError = ref('')

// 获取严重程度文本
const getSeverityText = (severity: string) => {
  switch (severity) {
    case 'HIGH': return '高风险'
    case 'MODERATE': return '中风险'
    case 'LOW': return '低风险'
    case 'UNKNOWN': return '未知风险'
    default: return '未知风险'
  }
}

// 获取严重程度CSS类
const getSeverityClass = (severity: string) => {
  switch (severity) {
    case 'HIGH': return 'high-risk'
    case 'MODERATE': return 'moderate-risk'
    case 'LOW': return 'low-risk'
    case 'UNKNOWN': return 'unknown-risk'
    default: return 'unknown-risk'
  }
}

// 检测相互作用
const checkInteractions = async () => {
  loading.value = true
  checked.value = false
  interactions.value = []
  
  try {
    // 获取药物名称列表
    const drugNames = medications.value.map((med: any) => {
      // 如果有RxNorm ID，优先使用RxNorm中的标准名称
      if (med.rxcui) {
        return getStandardDrugName(med.rxcui, med.name);
      }
      return Promise.resolve(med.name);
    });
    
    // 等待所有药物的标准名称获取完成
    const standardDrugNames = await Promise.all(drugNames);
    
    // 检测相互作用
    const results: any[] = []
    
    // 检查每对药物的相互作用
    for (let i = 0; i < standardDrugNames.length; i++) {
      for (let j = i + 1; j < standardDrugNames.length; j++) {
        const drug1 = standardDrugNames[i]
        const drug2 = standardDrugNames[j]
        
        // 验证药物名称是否合理
        if (!drug1 || drug1.length <= 1 || !drug2 || drug2.length <= 1) {
          console.warn('跳过无效的药物名称:', drug1, drug2);
          continue;
        }
        
        try {
          // 从openFDA获取相互作用数据
          const fdaData = await openfdaService.checkDrugDrugInteraction(drug1, drug2)
          
          // 生成风险描述和建议
          let interactionDetails = '';
          if (fdaData && fdaData.interactions && fdaData.interactions.length > 0) {
            interactionDetails = fdaData.interactions.map((item: any) => 
              item.details.join(' ')
            ).join(' ')
          }
          
          // 确定风险等级
          const severity = determineSeverity(interactionDetails, drug1, drug2);
          
          // 创建相互作用对象（所有药物组合都添加记录）
          const interactionObj = {
            id: Date.now() + Math.random(),
            drugs: [drug1, drug2],
            severity: severity,
            description: interactionDetails 
              ? `同时使用${drug1}和${drug2}可能会产生相互作用。`
              : `目前未在openFDA数据库中找到${drug1}和${drug2}之间明确的相互作用信息。`,
            recommendation: interactionDetails
              ? '建议密切监测患者的症状和体征，必要时调整剂量或更换药物。具体措施请咨询医生或药师。'
              : '虽然未发现明确的相互作用，但仍建议在使用过程中密切观察患者反应。',
            fdaData: fdaData?.interactions || []
          };
          
          results.push(interactionObj);
          
          // 移除自动进行AI分析的逻辑
          // 对于高风险药物相互作用，不再自动进行AI分析
          // 用户可以通过点击按钮手动触发AI分析
        } catch (error) {
          console.error(`检查 ${drug1} 和 ${drug2} 的相互作用时出错:`, error)
          
          // 即使出错也添加记录，显示为未知风险
          results.push({
            id: Date.now() + Math.random(),
            drugs: [drug1, drug2],
            severity: 'UNKNOWN',
            description: `检查${drug1}和${drug2}的相互作用时发生错误，请查看控制台了解详细信息。`,
            recommendation: '由于检查过程中出现错误，建议谨慎使用这两种药物的组合，并咨询医生或药师。',
            fdaData: []
          });
        }
      }
    }
    
    interactions.value = results
    checked.value = true
    // 保存相互作用结果到store
    store.commit('SET_INTERACTIONS', results)
  } catch (error) {
    console.error('检测相互作用时出错:', error)
    alert('检测相互作用时出错，请查看控制台了解详细信息')
  } finally {
    loading.value = false
  }
}

// 获取标准化药物名称
const getStandardDrugName = async (rxcui: string, fallbackName: string): Promise<string> => {
  try {
    const displayNameData = await rxnormService.getDisplayName(rxcui);
    // 验证返回的名称是否合理
    if (displayNameData && displayNameData.length > 1) {
      return displayNameData;
    }
    return fallbackName;
  } catch (error) {
    console.error(`获取药物 ${fallbackName} (RxCUI: ${rxcui}) 的标准名称时出错:`, error);
    return fallbackName;
  }
}

// 确定风险严重程度
const determineSeverity = (description: string, drug1?: string, drug2?: string) => {
  // 特殊情况处理：已知的高风险药物组合
  if (drug1 && drug2) {
    const drugA = drug1.toLowerCase();
    const drugB = drug2.toLowerCase();
    
    // 其他常见的高风险组合可以在这里添加
  }
  
  // 如果没有描述信息，返回低风险
  if (!description) {
    return 'LOW';
  }
  
  // 英文高风险关键词，移除了一些可能导致过度评估为高风险的关键词
  const highRiskKeywords = [
    // 严重性相关词汇
    'dangerous', 'severe', 'fatal', 'prohibited', 'avoid', 'life-threatening',
    'serious adverse reaction', 'serious adverse reactions', 
    'bleeding risk', 'toxicity increase', 'toxicity elevation',
    
    // 医学术语相关
    'contraindicated', 'contraindication', 'not recommended', 'absolute contraindication',
    'increased bleeding risk', 'prolonged bleeding time', 'bleeding time prolonged',
    
    // 药物相互作用相关（保留最明确的高风险表述）
    'significantly enhanced anticoagulant effect', 'significantly increased bleeding risk',
    'markedly increased bleeding risk'
  ]
  
  // 英文中等风险关键词，将一些原本可能判定为高风险的关键词移至此处
  const moderateRiskKeywords = [
    'caution', 'cautious', 'careful', 'carefully', 'monitor', 'monitoring', 
    'adjust dosage', 'adjust dose', 'dose adjustment', 'dosage adjustment',
    'possible increase', 'possible decrease', 'potential increase', 'potential decrease',
    'close observation', 'careful observation', 'careful monitoring',
    'regular check', 'regular monitoring', 'periodic monitoring',
    'risk increase', 'risk increased', 'increased risk', 'elevated risk',
    'effect enhancement', 'enhanced effect', 'effect increased',
    // 将一些药代动力学相关的关键词放在这里，使其不直接判定为高风险
    'significantly increased', 'enhanced anticoagulant effect', 
    'anticoagulant effect enhanced', 'anticoagulation enhanced', 'anticoagulation increased',
    'increase the effect', 'increase INR', 'inhibitors', 'inducers',
    'elevated bleeding risk', 'heightened bleeding risk'
  ]
  
  const lowerDescription = description.toLowerCase()
  
  for (const keyword of highRiskKeywords) {
    if (lowerDescription.includes(keyword.toLowerCase())) {
      return 'HIGH'
    }
  }
  
  for (const keyword of moderateRiskKeywords) {
    if (lowerDescription.includes(keyword.toLowerCase())) {
      return 'MODERATE'
    }
  }
  
  // 如果没有匹配到关键词，但有描述信息，返回中风险而不是低风险
  return 'MODERATE'
}

// 翻译FDA数据
const translateFdaData = async (interaction: any) => {
  if (!interaction.fdaData || interaction.fdaData.length === 0) return
  
  interaction.translating = true
  try {
    const translatedData = []
    
    for (const fdaInteraction of interaction.fdaData) {
      const translatedDetails = []
      
      for (const detail of fdaInteraction.details) {
        const translatedDetail = await tencentTranslateService.translateText(detail, 'zh')
        translatedDetails.push(translatedDetail)
      }
      
      translatedData.push({
        drug: fdaInteraction.drug,
        interactingDrug: fdaInteraction.interactingDrug,
        details: translatedDetails
      })
    }
    
    interaction.translatedFdaData = translatedData
  } catch (error) {
    console.error('翻译FDA数据时出错:', error)
    alert('翻译过程中出现错误，请稍后重试')
  } finally {
    interaction.translating = false
  }
}

// 导航到下一页
const goToNext = () => {
  router.push('/patient-info')
}
</script>

<style scoped>
.interactions-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.subtitle {
  color: #666;
  margin-bottom: 30px;
  text-align: center;
  font-size: 1.1rem;
}

.medications-list {
  background: transparent;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
  margin-bottom: 30px;
}

.medications-list h2 {
  color: #2c3e50;
  margin-top: 0;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  text-align: center;
}

.medications-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.medication-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 4px solid #3498db;
}

.medication-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
}

.medication-card h3 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.medication-card p {
  margin: 8px 0;
  color: #555;
  font-size: 0.95rem;
}

.rxnorm-info {
  background-color: #e3f2fd;
  padding: 8px;
  border-radius: 4px;
  margin-top: 10px;
  font-size: 0.9rem;
}

.rxnorm-info p {
  margin: 5px 0;
  color: #1976d2;
}

.remove-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
  margin-top: 10px;
  transition: background-color 0.3s;
}

.remove-btn:hover {
  background-color: #c0392b;
}

.interactions-results {
  background: white;
  border-radius: 10px;
  padding: 25px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  margin-bottom: 30px;
}

.interactions-results h2 {
  color: #2c3e50;
  margin-top: 0;
  border-bottom: 2px solid #2ecc71;
  padding-bottom: 10px;
}

.interaction-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border-left: 4px solid #2ecc71;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.interaction-item h3 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.risk-high {
  color: #e74c3c;
  font-weight: bold;
}

.risk-medium {
  color: #f39c12;
  font-weight: bold;
}

.risk-low {
  color: #27ae60;
  font-weight: bold;
}

.description-section, .recommendation-section, .fda-data-section, .ai-analysis-section {
  margin-bottom: 25px;
  padding: 15px;
  border-radius: 6px;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.description-section h4, .recommendation-section h4, .fda-data-section h4, .ai-analysis-section h4 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  font-size: 1.1rem;
}

.fda-interactions {
  margin-top: 15px;
}

.fda-interaction {
  background: #e8f4fc;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 15px;
  border-left: 3px solid #3498db;
}

.fda-interaction h5 {
  margin-top: 0;
  color: #2c3e50;
}

.translate-btn {
  background-color: #3498db;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 15px;
  transition: background-color 0.3s;
  font-weight: 500;
}

.translate-btn:hover:not(:disabled) {
  background-color: #2980b9;
}

.translate-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.ai-analyze-btn {
  background-color: #9b59b6;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.ai-analyze-btn:hover:not(:disabled) {
  background-color: #8e44ad;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.ai-analysis-loading {
  text-align: center;
  padding: 25px;
  color: #7f8c8d;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 1.1rem;
}

.ai-analysis-toggle {
  margin-top: 20px;
}

.toggle-btn {
  background-color: #34495e;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
  transition: background-color 0.3s;
}

.toggle-btn:hover:not(:disabled) {
  background-color: #2c3e50;
}

.detailed-analysis, .recommendation-summary {
  background: #e8f5e9;
  padding: 20px;
  border-radius: 6px;
  margin: 20px 0;
  border-left: 4px solid #27ae60;
}

.detailed-analysis h5, .recommendation-summary h5 {
  margin-top: 0;
  color: #2c3e50;
}

.api-info {
  background: #fff8e1;
  padding: 25px;
  border-radius: 10px;
  margin: 30px 0;
  border-left: 4px solid #ffc107;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.api-info h3 {
  margin-top: 0;
  color: #2c3e50;
}

.navigation-buttons {
  text-align: center;
  margin-top: 40px;
  padding: 20px 0;
}

.next-btn, .check-btn {
  background-color: #3498db;
  color: white;
  padding: 14px 28px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 17px;
  font-weight: 600;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  margin: 0 10px;
}

.next-btn:hover, .check-btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

.rxnorm-id {
  font-size: 0.9em;
  color: #7f8c8d;
  font-style: italic;
}

@media (max-width: 768px) {
  .interactions-container {
    padding: 15px;
  }
  
  .medications-grid {
    grid-template-columns: 1fr;
  }
  
  .medication-card, .interaction-item {
    padding: 15px;
  }
  
  .next-btn, .check-btn {
    width: 100%;
    padding: 12px;
    margin: 5px 0;
  }
}
</style>